<template>
  <div class="app-container bg-gray">
    <el-card class="box-1">
      <div class="header">
        <div>
          <el-select v-model="searchTerms.type" placeholder="题目类型" class="select" clearable @change="getData">
            <el-option :value="1" label="单选题"/>
            <el-option :value="2" label="多选题"/>
            <el-option :value="3" label="填空题"/>
          </el-select>
          <el-input v-model="searchTerms.searchValue" placeholder="请输入题目名称" class="search-input" @change="getData"/>
          <el-button type="success" class="do-btn" icon="el-icon-search" @click="getData">搜索</el-button>
        </div>
        <div class="right-btns">
          <router-link :to="`/exam/createQuestion?id=${id}`">
            <el-button type="warning">添加题目</el-button>
          </router-link>
          <router-link :to="`/exam/addFromQuestion?id=${id}`">
            <el-button type="warning" class="bg-green">从题库中选择</el-button>
          </router-link>
          <el-button type="info" icon="el-icon-tickets"><a :href="modelUrl" target="_blank">下载模板</a></el-button>
          <el-upload
            ref="upload"
            :limit="1"
            :show-file-list="false"
            :http-request="uploadFiles"
            :before-upload="beforeUpload"
            class="upload"
            accept=".xls,.xlsx"
            action="">
            <el-button :loading="uploadLoading" type="primary" icon="el-icon-printer">导入题目</el-button>
          </el-upload>
          <el-button type="danger" @click="toBatchDelete">批量删除</el-button>
        </div>
      </div>
      <el-table
        v-loading="tableLoading"
        ref="multipleTable"
        :data="tableData"
        :max-height="tableMaxHeight"
        border
        highlight-current-row
        @sort-change="handleSortChange"
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="43"/>
        <el-table-column prop="id" label="题号" width="120" header-align="center" align="center" sortable/>
        <el-table-column prop="name" label="题目标题" min-width="360"/>
        <el-table-column prop="type_name" label="题目类型" width="120" header-align="center" align="center"/>
        <el-table-column prop="fraction" label="分数" width="100" header-align="center" align="center"/>
        <el-table-column label="操作" width="220" header-align="center" align="center" fixed="right">
          <template slot-scope="scope">
            <router-link :to="`/exam/questionDetails?id=${id}&itemId=${scope['row']['id']}`">
              <el-button type="primary" size="small" icon="el-icon-search" circle/>
            </router-link>
            <router-link :to="`/exam/modifyQuestion?id=${id}&itemId=${scope['row']['id']}`">
              <el-button type="primary" class="bg-green" size="small" icon="el-icon-edit" circle/>
            </router-link>
            <el-button type="danger" size="small" icon="el-icon-delete" circle @click="toDelete(scope.row)"/>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        :current-page.sync="currentPage"
        :page-size="pageSize"
        :page-sizes="pageSizes"
        :total="total"
        class="pagination"
        layout="total, sizes, prev, pager, next, jumper"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"/>
    </el-card>
  </div>
</template>

<script>
import { handleSortChange, handleSizeChange, handleCurrentChange, parseTime } from '@/utils/table'
import { fileToBase64 } from '@/utils/index'
export default {
  data() {
    return {
      searchTerms: {
        type: '',
        searchValue: ''
      },

      // 试卷id
      id: null,
      // 模板下载地址
      modelUrl: this.$store.getters.serverUrl + '/admin/exam/downloadExcelDemo?token=' + this.$store.getters.token,
      // 上传遮罩
      uploadLoading: false,

      // 表格相关数据
      tableMaxHeight: document.documentElement.clientHeight - 380,
      tableLoading: false,
      currentPage: 1,
      pageSize: this.$store.getters.userInfo.pageSize,
      pageSizes: [10, 20, 50, 100, 1000],
      total: 0,
      tableData: [],
      multipleSelection: []
    }
  },
  created() {
    this.id = this.$route.query.id;
    this.getData();
  },
  methods: {
    handleCurrentChange, handleSizeChange, handleSortChange, parseTime, fileToBase64,
    getData(order) {
      this.tableLoading = true
      order || (order = {})
      const url = 'exam/testPaperSubjectList'
      const data = {
        id: this.id,
        pageNo: this.currentPage,
        pageSize: this.pageSize,
        search: this.searchTerms.searchValue,
        type: this.searchTerms.type
      }
      order.sortName && (data.sortName = order.sortName);
      order.sortOrder && (data.sortOrder = order.sortOrder);
      this.$store.dispatch('GetConnect', { url, data }).then(res => {
        this.tableData = res.data.rows
        this.total = res.data.total
        this.tableLoading = false
      }).catch(e => {
        this.tableLoading = false
        this.$message.error(e.msg + ',请刷新或联系管理员')
      })
    },

    // table多选
    handleSelectionChange(val) {
      this.multipleSelection = val
    },

    toDelete(row){
      this.$confirm('此操作将在试卷中删除所选题目, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const url = 'exam/delTestItem';
        const data = {
          id: this.id,
          itemId: row.id
        }
        this.$store.dispatch('GetConnect', { url, data }).then(res => {
          this.$message.success(res.msg)
          this.getData()
        }).catch((err) => {
          this.$message.error(err.msg)
        })
      })
    },

    toBatchDelete() {
      if (this.multipleSelection.length === 0) {
        this.$message.error('请选择要删除的题目')
        this.dialogVisible = false
      } else {
        this.$confirm('此操作将在试卷中删除所选题目, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          const url = 'exam/batchDelId'
          const data = {
            id: this.id,
            itemIds: []
          }
          this.multipleSelection.forEach(item => {
            data.itemIds.push(item.id)
          })
          data.itemIds = data.itemIds.join(',')
          this.$store.dispatch('GetConnect', { url, data }).then(res => {
            this.$message.success(res.msg);
            this.getData();
          }).catch((err) => {
            this.$message.error(err.msg)
          })
        })
      }
    },

    beforeUpload(file) {
      // const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      // if (!isExcel) {
      //   this.$message.error('导入失败,请检查导入的文件是否是.xlsx或.xls文件')
      // }
      // return isExcel
    },
    uploadFiles(item) {
      this.uploadLoading = true
      const url = 'exam/batchUploadItem'
      this.fileToBase64(item.file).then(res=>{
        const data = {
          id: this.id,
          file: res
        }
        this.$store.dispatch('UploadFile', { url, data }).then((res) => {
          this.$message.success(res.msg)
          this.uploadLoading = false
          this.getData()
          this.$refs.upload.clearFiles()
        }).catch((res) => {
          this.uploadLoading = false
          this.$message.error(res.msg)
        })
      });
    }
  }
}
</script>

<style lang="scss" type="text/scss" scoped>
@import '../../../../styles/index.scss';
.box-1 {
  .model {
    .el-card {
      color: #fff;
      background-color: $panGreen;
      span {
        font-size: 14px;
      }
      div {
        font-size: 24px;
        margin-top: 10px;
      }
    }
  }
  .header {
    @include flex-row(center, space-between);
    flex-wrap: wrap;
    padding-bottom: 15px;
    div {
      @include flex-row(center, flex-start);
      flex-wrap: wrap;
      .select {
        padding-right: 15px;
        width: 150px;
      }
      .picker {
        margin-right: 15px;
        width: 300px;
      }
      .do-btn {
        @extend .bg-green;
        margin-left: 6px;
      }
      .search-input {
        width: 180px;
      }
    }

    .right-btns{
      .el-button{
        margin-left: 10px;
      }
    }
  }
}
.dialog {
  .content {
    text-align: center;
    .el-select {
      width: 300px;
    }
    .text {
      padding-bottom: 20px;
      .el-radio-group {
        padding-left: 15px;
      }
    }
  }
}
</style>

